//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include <bsp.h>
#include <6410addr.h>

// Here, 0 <= number <= 99
#define Hex2BCD(number) ((((number) / 10) << 4) + ((number) % 10))
#define BCD2Hex(number) ((((number) >> 4) & 0xf) * 10 + ((number) & 0xf))

EXTERN_C DECL_CODEINIT void CDECL InitRTC()
{
    //LNOTENOTE: No need sync RTC Time from PMU
    RTCTime t;
    t.uYear = 2009;
    t.uMonth = 4;
    t.uDate = 8;
    t.uHours = 0;
    t.uMinutes = 0;
    t.uSeconds = 0;
    BspSetRTCTime(&t);
}

EXTERN_C void CDECL BspGetRTCTime(RTCTime *pRTCTime)
{
    uint32_t uYear = rBCDYEAR;
    uint32_t uMon  = rBCDMON;
    uint32_t uDate = rBCDDATE;
    uint32_t uHour = rBCDHOUR;
    uint32_t uMin  = rBCDMIN;
    uint32_t uSec  = rBCDSEC;

    pRTCTime->uYear     = BCD2Hex(uYear & 0xff) + 2000;//Year
    pRTCTime->uMonth    = BCD2Hex(uMon  & 0x1f); //Month
    pRTCTime->uDate     = BCD2Hex(uDate & 0x3f); //Day of Month

    pRTCTime->uHours    = BCD2Hex(uHour & 0x3f); //Hour
    pRTCTime->uMinutes  = BCD2Hex(uMin  & 0x7f); //Minnute
    pRTCTime->uSeconds  = BCD2Hex(uSec  & 0x7f); //Second
}

EXTERN_C void CDECL BspSetRTCTime(const RTCTime *pRTCTime)
{
    //Valid day of week
//    if (pRTCTime->uWeekday < 1 || pRTCTime->uWeekday > 7)
//        pRTCTime->uWeekday = 1;

//    if (pRTCTime->uYear < 2000) pRTCTime->uYear = 2000;
//    if (pRTCTime->uYear > 2099) pRTCTime->uYear = 2099;


    rRTCCON  = rRTCCON  & ~(0xf)  | 0x1; //No reset, Merge BCD counters, 1/32768, RTC Control enable

    // Note: All the registers below store BCD values
    rBCDYEAR = rBCDYEAR & ~(0xff) | (Hex2BCD(pRTCTime->uYear - 2000)) ;
    rBCDMON  = rBCDMON  & ~(0x1f) | (Hex2BCD(pRTCTime->uMonth));
    rBCDDATE = rBCDDATE & ~(0x3f) | (Hex2BCD(pRTCTime->uDate));

    rBCDHOUR = rBCDHOUR & ~(0x3f) | (Hex2BCD(pRTCTime->uHours));
    rBCDMIN  = rBCDMIN  & ~(0x7f) | (Hex2BCD(pRTCTime->uMinutes));
    rBCDSEC  = rBCDSEC  & ~(0x7f) | (Hex2BCD(pRTCTime->uSeconds));

    rRTCCON  = 0x0; //No reset, Merge BCD counters, 1/32768, RTC Control disable
}
